# wifi操作

import time

import network
import machine
import zz_code
import zz_led
import zz_log
import urequests

log = zz_log.of()

led = zz_led.of()


def of():
    return ZZ_WIFI()


def set_info(ssid, pwd):
    zz_code.config_set("wifi_ssid", ssid)
    zz_code.config_set("wifi_pwd", pwd)


def update_machine_time():
    """
    获取服务器时间更新到设备
    :return:
    """
    rtc = machine.RTC()
    now = rtc.datetime()
    if now[0] >= 2024:
        log.debug(f"服务器时间正常，无需要更新")
        return

    url = 'https://app.lai-m.com/sys/app/api/info'
    res = urequests.get(url)
    content = res.text
    r = zz_code.json_to_return(content)
    if r.err():
        log.error(r.to_json())
        return

    server_time = r.get_data("api_date")  # 服务器时间
    log.debug(f"服务器时间：{server_time}")
    server_time = server_time.replace(' ', '-')
    server_time = server_time.replace(':', '-')
    # 转数组
    # （年、月、日、工作日、小时、分钟、秒、亚秒）
    server_time_arr = server_time.split('-')
    server_time_arr.insert(3, 0)
    server_time_arr.insert(7, 0)
    arr_new = []
    for e in server_time_arr:
        # 转数字
        arr_new.append(int(e))
    # 更新
    machine.RTC().datetime(arr_new)


class ZZ_WIFI():
    def __init__(self):
        self.wlan = network.WLAN(network.STA_IF)
        self.wlan.active(True)
        # self.timer2 = Timer(2)
        self.disconnect_callback = None
        self.connecting = False
        self.enable = True
        self.test = ""

    def service_close(self):
        log.debug(f"wifi服务关闭")
        self.enable = False

    def service_open(self):
        log.debug(f"wifi服务开启")
        self.enable = True

    def service_is(self, enable):
        res = self.enable == enable
        if not enable and res:
            log.debug("wifi服务已关闭")
        return res

    # 连接wifi 返回结果
    def begin_connect(self):
        conn = False

        if self.service_is(False):
            return conn

        if self.connecting:
            log.debug("wifi连接中")
            return conn

        self.connecting = True
        if self.wlan.isconnected():
            log.debug('wifi已连接')
            conn = True
        else:
            log.debug('wifi未连接')
            ssid = zz_code.config_get("wifi_ssid")
            pwd = zz_code.config_get("wifi_pwd")

            if ssid == "" or pwd == "":
                log.debug('未配置wifi密码')
                self.connecting = False
                return False

            led.led_dodge(100)
            self.wlan.active(False)  # 关闭Wi-Fi
            self.wlan.active(True)

            log.debug(f'开始连接---ssid: {ssid}, pwd: {pwd}')
            self.wlan.connect(ssid, pwd)
            connect_max = 10
            for i in range(0, connect_max, 1):
                if self.service_is(False):
                    break

                if self.wlan.isconnected():
                    break

                time.sleep(1)
                log.debug(f"wifi尝试连接: {i}")

            conn = self.wlan.isconnected()

        led.led_dodge_stop()
        if conn:
            log.debug("wifi连接成功")
            print(self.wlan.ifconfig())
            self.connected()

        self.connecting = False
        return conn

    # wifi连接成功
    def connected(self):
        led.led_dodge_stop()
        led.led_blue(True)
        # 定时检查wifi是否断开
        zz_code.thread_func(self.check_connect)
        # self.timer2.init(period=3000, mode=Timer.PERIODIC, callback=self.check_connect)

    # wifi检查连接状态，断开执行重连逻辑
    def check_connect(self):
        log.debug("开启检查wifi连接状态")
        while True:
            if self.wlan.isconnected():
                # wifi连接中，3秒后再检查
                # log.debug("wifi连接中，3秒后再检查")
                time.sleep(3)
                continue

            log.debug("wifi断开，执行disconnect_callback")
            if self.disconnect_callback is not None:
                self.disconnect_callback()
            break

    # wifi断开回调
    def bind_disconnect_callback(self, func):
        self.disconnect_callback = func
